package org.pemobbe.gruo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jxl.Workbook;
import jxl.format.Colour;
import jxl.write.DateTime;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.pemobbe.gruo.beans.Car;

public class ExportServiceBean {

	private static List<Car> cars = new ArrayList<Car>();

	static {
		for (int i = 2; i < 5; i++) {
			cars.add(new Car("peugeot", i + "07"));
		}
	}

	public ByteArrayOutputStream generateExcelReport() throws IOException, WriteException {

		// Stream containing excel data
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

		// Create Excel WorkBook and Sheet
		WritableWorkbook workBook = Workbook.createWorkbook(outputStream);
		WritableSheet sheet = workBook.createSheet("Car List", 0);

		// Generates Headers Cells
		WritableFont headerFont = new WritableFont(WritableFont.TAHOMA, 10, WritableFont.BOLD);
		WritableCellFormat headerCellFormat = new WritableCellFormat(headerFont);
		headerCellFormat.setBackground(Colour.PALE_BLUE);
		sheet.addCell(new Label(1, 1, "Mark", headerCellFormat));
		sheet.addCell(new Label(2, 1, "Model", headerCellFormat));

		// Generates Data Cells
		WritableFont dataFont = new WritableFont(WritableFont.TAHOMA, 10);
		WritableCellFormat dataCellFormat = new WritableCellFormat(dataFont);
		int currentRow = 2;
		for (Car user : ExportServiceBean.cars) {
			sheet.addCell(new Label(1, currentRow, user.getMark(), dataCellFormat));
			sheet.addCell(new Label(2, currentRow, user.getModel(), dataCellFormat));
			sheet.addCell(new DateTime(3, currentRow, new Date()));
			currentRow++;
		}

		// Write & Close Excel WorkBook
		workBook.write();
		workBook.close();

		return outputStream;
	}
}
